<script setup lang="ts">
  import { PropType, ref, watch } from 'vue'
  import { FormInstance } from 'element-plus'
  import { FieldForm } from '../types'
  import _ from 'lodash'
  import HButton from '@/components/common/button/HButton.vue'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
  import HModal from '@/components/common/Modal/HModal.vue'
  import useFormValidateService from '@/service/common/useFormValidate/useFormValidateService'
  import HLink from '@/components/common/link/HLink.vue'

  const props = defineProps({
    modalTitle: {
      type: String,
      required: true,
    },
    isAdd: {
      type: Boolean,
      required: true,
    },
    form: {
      type: Object as PropType<FieldForm>,
      required: true,
    },
    modelValue: {
      type: Boolean,
      default: () => false,
    },
  })

  const emits = defineEmits<{
    (e: 'updated', value: FieldForm): void
    (e: 'update:modelValue', value: boolean): void
  }>()

  const { handleFormValidate, resetFormValidateResult, formValidateResult } =
    useFormValidateService([
      { name: 'name', isSelect: false },
      { name: 'text', isSelect: false },
    ])

  // 字段类型下拉选项
  const fieldTypeOptions = ref([
    { name: '文本', val: 1 },
    { name: '多行文本', val: 2 },
    { name: '单选', val: 3 },
    { name: '多选', val: 4 },
    { name: '多图', val: 5 },
    { name: '附件', val: 6 },
    { name: '视频', val: 7 },
    { name: '评分', val: 8 },
  ])

  // 表单
  const __form = ref<FieldForm>({
    type: 1,
    contentVos: [
      {
        id: '',
        val: '',
      },
    ],
    delContentIds: [],
    id: null,
    uploadSize: 100,
    name: '',
    required: true,
    sort: 0,
    status: false, //false-启用，true-禁用
    tip: '',
    uploadQty: 1,
    num:0
  })

  // 验证规则
  const rules = ref({
    name: [{ required: true, message: '请输入字段名称', trigger: ['blur', 'change'] }],
    text: [{ required: true, message: '请输入字段内容', trigger: ['blur', 'change'] }],
    uploadQty: [
      { required: false, message: '请输入上传数量', trigger: ['blur', 'change'] },
      {
        validator: (rule, value: string, callback) => {
          if (!/^[+]{0,1}(\d+)$/g.test(String(__form.value.uploadQty))) {
            callback(new Error('格式错误'))
          }
          if (__form.value.uploadQty > 10) {
            callback(new Error('最多上传10张'))
          } else {
            callback()
          }
        },
        trigger: ['blur', 'change'],
      },
    ],
    uploadSize: [
      { required: false, message: '请输入最大尺寸', trigger: ['blur', 'change'] },
      {
        pattern: /^[+]{0,1}(\d+)$/g,
        message: '格式错误',
        trigger: ['blur', 'change'],
      },
    ],
    sort: [
      { required: false, message: '请输入字段排序', trigger: ['blur', 'change'] },
      {
        pattern: /^[+]{0,1}(\d+)$/g,
        message: '格式错误',
        trigger: ['blur', 'change'],
      },
    ],
  })

  // 弹窗的显示状态
  const visible = ref(props.modelValue)

  // 新增字段内容
  const addText = () => {
    __form.value.contentVos.push({
      val: '',
      id: '',
    })
  }

  // 删除字段内容
  const handleDelFieldContent = (index: number, obj: (typeof __form.value.contentVos)[0]) => {
    __form.value.contentVos.splice(index, 1)
    if (obj.id) {
      if (!__form.value.delContentIds) {
        __form.value.delContentIds = [obj.id]
        return false
      }
      __form.value.delContentIds.push(obj.id)
    }
  }

  // 字段编辑表单组件实例
  const fieldEditFormRef = ref<FormInstance>()

  /**
   * 保存字段
   */
  const saveField = async () => {
    if (![5, 6, 7].includes(__form.value.type)) {
      __form.value.uploadSize = 100
      __form.value.uploadQty = 1
    }
    if (!fieldEditFormRef.value) {
      return false
    }
    try {
      await fieldEditFormRef.value.validate()
      if (![3, 4].includes(__form.value.type)) {
        __form.value.contentVos = []
      }
      emits('updated', _.cloneDeep(__form.value))
      visible.value = false
      emits('update:modelValue', visible.value)
    } catch (e) {
      // 不可删除catch块，否则表单校验失败会导致控制台报错，只有添加了catch块才不会报错，并且在catch里什么都不用做
    }
  }

  /**
   * 取消按钮点击事件
   */
  const onClose = () => {
    resetFormValidateResult()
    visible.value = false
    emits('update:modelValue', visible.value)
  }

  /**
   * 上传数量输入事件
   * @param {Event} e - Event
   */
  const handleInputUploadNum = (e: Event) => {
    ;(e.target as HTMLInputElement).value = (e.target as HTMLInputElement).value.replace(
      /[^\d]/g,
      '',
    )

    if (Number((e.target as HTMLInputElement).value) > 10) {
      ;(e.target as HTMLInputElement).value = '10'
      __form.value.uploadQty = 10
    }
  }
  const limitNum = (val, n) => {
    if (val > n) {
      val = n
    } else if (val == 0) {
      val = 1
    }
    if (n == 100) {
      __form.value.uploadSize = val
    } else {
      __form.value.uploadQty = val
    }
  }
  watch(
    props,
    (value) => {
      __form.value = _.cloneDeep(value.form)
      visible.value = value.modelValue
    },
    { immediate: true, deep: true },
  )
</script>

<template>
  <div>
    <span>
      <slot></slot>
    </span>

    <!-- 添加/编辑  字段弹窗 -->
    <HModal class="field-dialog" v-model="visible" width="500" @close="onClose">
      <template #header>
        <h3>{{ props.modalTitle }}</h3>
      </template>
      <div class="form-text module-form" element-loading-text="加载中...">
        <el-form
          label-width="90"
          ref="fieldEditFormRef"
          :rules="rules"
          :model="__form"
          class="modal_form_content"
          @validate="handleFormValidate"
        >
          <!--字段名称-->
          <el-form-item
            label="字段名称"
            class="form_input_item"
            :class="{ error_form_item: !formValidateResult['name'] }"
            prop="name"
          >
            <el-input v-model="__form.name" clearable placeholder="请输入名称" />
          </el-form-item>

          <!--字段类型-->
          <el-form-item label="字段类型" class="form_select_item">
            <el-select v-model="__form.type" placeholder="Select" :disabled="!props.isAdd">
              <el-option
                v-for="item in fieldTypeOptions"
                :key="item.val"
                :label="item.name"
                :value="item.val"
              />
            </el-select>
          </el-form-item>

          <!--字段排序-->
          <el-form-item label="字段排序" class="form_input_item" prop="sort">
            <el-input v-model="__form.sort" clearable placeholder="请输入字段排序" />
          </el-form-item>

          <!--提示信息-->
          <el-form-item label="提示信息" class="form_input_item">
            <el-input v-model="__form.tip" clearable placeholder="请输入提示信息" />
          </el-form-item>

          <!--最大尺寸-->
          <el-form-item
            label="最大尺寸(MB)"
            class="form_input_item"
            prop="uploadSize"
            v-if="__form.type === 5 || __form.type === 6 || __form.type === 7"
          >
            <el-input
              v-model="__form.uploadSize"
              clearable
              placeholder="请输入最大尺寸"
              @input="limitNum(__form.uploadSize, 100)"
              @change="__form.uploadSize ? '' : (__form.uploadSize = 1)"
              type="number"
            />
          </el-form-item>

          <!--上传数量-->
          <el-form-item
            label="上传数量"
            prop="uploadQty"
            class="form_input_item"
            v-if="__form.type === 5 || __form.type === 6 || __form.type === 7"
          >
            <el-input
              v-model="__form.uploadQty"
              clearable
              placeholder="请输入数量(最多10张)"
              @input="limitNum(__form.uploadQty, 10)"
              @change="__form.uploadQty ? '' : (__form.uploadQty = 1)"
              type="number"
            />
          </el-form-item>

          <!--字段内容-->
          <el-form-item
            :required="true"
            label="字段内容"
            v-if="__form.type === 4 || __form.type === 3"
            class="form_height_22_item"
          >
            <HPlainButton class="add" :padding-lr="6" :height="22" @click="addText"
              >+ 新增
            </HPlainButton>
          </el-form-item>
          <el-scrollbar max-height="220" v-if="__form.type === 4 || __form.type === 3">
            <div style="display: flex; flex-direction: column; gap: 12px">
              <div
                v-for="(item, index) in __form.contentVos"
                :key="index"
                style="margin-right: 10px"
              >
                <el-form-item
                  :prop="`contentVos[${index}][val]`"
                  :rules="rules.text"
                  class="form_input_item"
                  :label="`${index + 1}、`"
                  :required="false"
                >
                  <div style="display: flex; align-items: center; width: 100%; gap: 5px">
                    <el-input
                      v-model="item.val"
                      clearable
                      placeholder="请输入字段内容"
                      maxlength="20"
                    />
                    <div style="width: 24px; height: 28px; line-height: 28px">
                      <HLink type="error" @click="handleDelFieldContent(index, item)">删除</HLink>
                    </div>
                  </div>
                </el-form-item>
              </div>
            </div>
          </el-scrollbar>

          <!--是否必填-->
          <el-form-item label="是否必填" class="form_switch_item">
            <div class="switch_container">
              <el-switch v-model="__form.required" />
              <span v-if="__form.required" class="text">是</span>
              <span v-else class="text">否</span>
            </div>
          </el-form-item>

          <!--字段状态-->
          <el-form-item label="字段状态" class="form_switch_item">
            <div class="switch_container">
              <el-switch v-model="__form.status" :active-value="false" :inactive-value="true" />
              <span v-if="__form.status" class="text">禁用</span>
              <span v-else class="text">启用</span>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <template #footerRight>
        <HButton is-modal type="primary" @click="saveField">保存</HButton>
        <HButton is-modal @click="onClose">取消</HButton>
      </template>
    </HModal>
  </div>
</template>
